//
//  CurrentOrder_Arrive.m
//  XJMTechnician
//
//  Created by Mr.hu on 2017/10/27.
//  Copyright © 2017年 Mr.hu. All rights reserved.
//

#import "CurrentOrder_Arrive.h"
#import "NewsRemindVC.h"

#import "CommonUtility.h"
#import "MANaviRoute.h"
#import "JGNavigationService.h"
#import "CurrentServiceVC.h"

static const NSString *RoutePlanningViewControllerStartTitle       = @"起点";
static const NSString *RoutePlanningViewControllerDestinationTitle = @"终点";
static const NSInteger RoutePlanningPaddingEdge                    = 20;

@interface CurrentOrder_Arrive ()<MAMapViewDelegate, AMapSearchDelegate,CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UIView *Current_backView;
@property (weak, nonatomic) IBOutlet UILabel *Order_Addresslab;
@property (weak, nonatomic) IBOutlet UILabel *Order_Messagelab;
@property (weak, nonatomic) IBOutlet UIButton *Order_DialTelephone;

@property (weak, nonatomic) IBOutlet UIButton *Order_StartService;
@property (weak, nonatomic) IBOutlet UIView *Order_CustomerView; //设置背景为透明
@property (weak, nonatomic) IBOutlet UIView *MapBack_View;

/** 注释 **/
@property (strong, nonatomic) CLLocationManager * locationManager;
/* 路径规划类型 */
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) AMapRoute *route;

/* 当前路线方案索引值. */
@property (nonatomic) NSInteger currentCourse;
/* 路线方案个数. */
@property (nonatomic) NSInteger totalCourse;

@property (nonatomic, strong) UIBarButtonItem *previousItem;
@property (nonatomic, strong) UIBarButtonItem *nextItem;

/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

/* 用于显示当前路线方案. */
@property (nonatomic) MANaviRoute * naviRoute;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;

@end

@implementation CurrentOrder_Arrive

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [AMapServices sharedServices].apiKey =ApiKey;
    
    [self.navigationController setNavigationBarHidden:NO];
    [self addLeftBtn:[UIImage imageNamed:@"fanhui"] Action:@selector(backToPrevious)];
    [self addRightLabel:@"刷新" Action:@selector(RefreshCurrentOrder)];
    self.title = @"当前订单";
//    self.Order_CustomerView.backgroundColor = RGBA(51, 51, 51, 0.7);
    self.Order_StartService.layer.cornerRadius = 22;
    self.Order_Addresslab.layer.masksToBounds = YES;
    
    [self mapshowInformation];
    
    [self navigationShowCustomerInformation]; //导航栏显示
}

- (void)RefreshCurrentOrder{
    
    if ([self.CustomerOrder_Dict isKindOfClass:[NSDictionary class]]) {
     
    [XJHttpClass TeachCheckStartServiceorder_id:self.CustomerOrder_Dict[@"order_id"] u_lon:self.CustomerOrder_Dict[@"u_lon"] u_lat:self.CustomerOrder_Dict[@"u_lat"] token:[XJToolClass getToken] andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            self.Order_StartService.backgroundColor = RGBA(213, 32, 30, 1);
            self.Order_StartService.enabled = YES;
        }
    }];
    }
}

-(void)navigationShowCustomerInformation{
    
    self.Order_Addresslab.text = self.CustomerOrder_Dict[@"address"];
    if (self.CustomerOrder_Dict[@"user_note"]) {
        self.Order_Messagelab.text = [NSString stringWithFormat:@"用户留言 : %@",self.CustomerOrder_Dict[@"user_note"]];
    }
}

- (void)mapshowInformation{
    
    _locationManager = [[CLLocationManager alloc] init];
    
    if([CLLocationManager locationServicesEnabled]){
        
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
            [_locationManager requestWhenInUseAuthorization];
        }
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        CLLocationDistance distance = 10.0;
        _locationManager.distanceFilter = distance;
        [_locationManager startUpdatingLocation];
    
    }else{
        [XJToolClass showLocationOpenTip:self];
    }
}

#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coord=location.coordinate;//位置坐标
    [_locationManager stopUpdatingLocation];
    //    NSString *positionString = [NSString stringWithFormat:@"%f,%f",coord.latitude,coord.longitude];
    //    [self getNearStation:positionString];
    
    CLLocation *transLocation = [[CLLocation alloc]initWithLatitude:coord.latitude longitude:coord.longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:transLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       if (error) {
                       }
                       if (placemarks.count>0) {
                           CLPlacemark *place = [placemarks objectAtIndex:0];
                           NSString *city = place.locality;
                           NSString *area = place.subLocality;
                           if (!city) {
                               //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                               city = place.administrativeArea;
                           }
                           
//                           self.PlaceDict = @{@"longtitudeplace":[NSString stringWithFormat:@"%f",coord.longitude],@"tatiduteplace":[NSString stringWithFormat:@"%f",coord.latitude],@"addressplace":city};
                           
           }
     }];
    
    
    self.startCoordinate        = CLLocationCoordinate2DMake(coord.latitude, coord.longitude);
    
    self.destinationCoordinate  = CLLocationCoordinate2DMake(self.Customer_latitude.floatValue, self.Customer_longtitude.floatValue);
    [self addLeftBtn:[UIImage imageNamed:@"fanhui"] Action:@selector(backToPrevious)];
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    
    [self.Current_backView addSubview:self.mapView];
    
    //self.mapView.showTraffic = YES;
    
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    [self initToolBar];
    [self addDefaultAnnotations];
    [self updateCourseUI];
    [self updateDetailUI];
    
    [self searchRoutePlanningDrive];
    
}

// 错误信息
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    //    [self getNearStation:nil];
}


#pragma mark - do search
- (void)searchRoutePlanningDrive
{
    self.startAnnotation.coordinate = self.startCoordinate;
    self.destinationAnnotation.coordinate = self.destinationCoordinate;
    
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
    navi.strategy = 5;
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapDrivingRouteSearch:navi];
}

#pragma mark - action handle
/* 切到上一个方案路线. */
- (void)previousCourseAction
{
    if ([self decreaseCurrentCourse])
    {
        [self clear];
        
        [self updateCourseUI];
        
        [self presentCurrentCourse];
    }
}

/* 切到下一个方案路线. */
- (void)nextCourseAction
{
    if ([self increaseCurrentCourse])
    {
        [self clear];
        
        [self updateCourseUI];
        
        [self presentCurrentCourse];
    }
}

#pragma mark - Utility
/* 更新"上一个", "下一个"按钮状态. */
- (void)updateCourseUI
{
    /* 上一个. */
    self.previousItem.enabled = (self.currentCourse > 0);
    
    /* 下一个. */
    self.nextItem.enabled = (self.currentCourse < self.totalCourse - 1);
}

/* 更新"详情"按钮状态. */
- (void)updateDetailUI
{
    self.navigationItem.rightBarButtonItem.enabled = self.route != nil;
}

- (void)updateTotal
{
    self.totalCourse = self.route.paths.count;
}

- (BOOL)increaseCurrentCourse
{
    BOOL result = NO;
    
    if (self.currentCourse < self.totalCourse - 1)
    {
        self.currentCourse++;
        
        result = YES;
    }
    
    return result;
}

- (BOOL)decreaseCurrentCourse
{
    BOOL result = NO;
    
    if (self.currentCourse > 0)
    {
        self.currentCourse--;
        
        result = YES;
    }
    
    return result;
}

/* 展示当前路线方案. */
- (void)presentCurrentCourse
{
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.startAnnotation.coordinate.latitude longitude:self.startAnnotation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.destinationAnnotation.coordinate.latitude longitude:self.destinationAnnotation.coordinate.longitude]];
    [self.naviRoute addToMapView:self.mapView];
    
    /* 缩放地图使其适应polylines的展示. */
    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                        edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
                           animated:YES];
}

/* 清空地图上已有的路线. */
- (void)clear
{
    [self.naviRoute removeFromMapView];
}

/* 进入详情页面
- (void)gotoDetailForRoute:(AMapRoute *)route type:(AMapRoutePlanningType)type
{
//    RouteDetailViewController *routeDetailViewController = [[RouteDetailViewController alloc] init];
//    routeDetailViewController.route      = route;
//    routeDetailViewController.routePlanningType = type;
    
//    [self.navigationController pushViewController:routeDetailViewController animated:YES];
}
*/

#pragma mark - MAMapViewDelegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.lineDash = YES;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 8;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 10;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        poiAnnotationView.image = nil;
        
        if ([annotation isKindOfClass:[MANaviAnnotation class]])
        {
            switch (((MANaviAnnotation*)annotation).type)
            {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    poiAnnotationView.image = [UIImage imageNamed:@"car"];
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
        }else
        {
            /* 起点. */
            if ([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerStartTitle])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"startPoint"];
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerDestinationTitle])
            {
                poiAnnotationView.image = [UIImage imageNamed:@"endPoint"];
            }
            
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
//    NSLog(@"Error: %@ - %@", error, [ErrorInfoUtility errorDescriptionWithCode:error.code]);
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    
    self.route = response.route;
    [self updateTotal];
    self.currentCourse = 0;
    
    [self updateCourseUI];
    [self updateDetailUI];
    
    if (response.count > 0)
    {
        [self presentCurrentCourse];
    }
}

#pragma mark - Initialization
- (void)initToolBar
{
    UIBarButtonItem *flexbleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                                 target:self
                                                                                 action:nil];
    /* 上一个. */
    UIBarButtonItem *previousItem = [[UIBarButtonItem alloc] initWithTitle:@"上一个"
                                                                     style:UIBarButtonItemStylePlain
                                                                    target:self
                                                                    action:@selector(previousCourseAction)];
    self.previousItem = previousItem;
    
    /* 下一个. */
    UIBarButtonItem *nextItem = [[UIBarButtonItem alloc] initWithTitle:@"下一个"
                                                                 style:UIBarButtonItemStylePlain
                                                                target:self
                                                                action:@selector(nextCourseAction)];
    self.nextItem = nextItem;
    
    self.toolbarItems = [NSArray arrayWithObjects:flexbleItem, previousItem, flexbleItem, nextItem, flexbleItem, nil];
}

- (void)addDefaultAnnotations
{
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = (NSString*)RoutePlanningViewControllerStartTitle;
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      = (NSString*)RoutePlanningViewControllerDestinationTitle;
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    [self.mapView addAnnotation:startAnnotation];
    [self.mapView addAnnotation:destinationAnnotation];
}

- (void)remindNewsMeth{
    NewsRemindVC * newsremind = [[NewsRemindVC alloc]init];
    [self.navigationController pushViewController:newsremind animated:YES];
}

#pragma mark - action handle
//一键求助
- (IBAction)CommentHelpMeth:(id)sender {
    
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@",@"110"];
    CGFloat version = [[[UIDevice currentDevice]systemVersion]floatValue];
    if (version >= 10.0) {
        /// 大于等于10.0系统使用此openURL方法
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
    }
}

//导航
- (IBAction)NavigationOrder_meth:(id)sender {
    
    CLLocationCoordinate2D coordinte = CLLocationCoordinate2DMake((CLLocationDegrees)self.Customer_latitude.doubleValue, (CLLocationDegrees)self.Customer_latitude.doubleValue);
    [JGNavigationService navWithViewController:self WithEndLocation:coordinte andAddress:@""];
}

//开始服务
- (IBAction)Order_StartServiceMeth:(UIButton *)sender {
    
    if (self.CustomerOrder_Dict[@"order_id"]) {
      
    [XJHttpClass teachOnclickedStartServicetoken:[XJToolClass getToken] order_id:self.CustomerOrder_Dict[@"order_id"] andFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            
            CurrentServiceVC * currentservice = [[CurrentServiceVC alloc]init];
            currentservice.CurrentOrder_Information = self.CustomerOrder_Dict;
            currentservice.CurrentOrder_ID = self.CustomerOrder_Dict[@"order_id"];
            [self.navigationController pushViewController:currentservice animated:YES];
        }
      }];
    }
}

//打电话
- (IBAction)MakingCallMeth:(id)sender {
    
    if (self.CustomerOrder_Dict[@"mobile"]) {
    
    NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@",self.CustomerOrder_Dict[@"mobile"]];
    CGFloat version = [[[UIDevice currentDevice]systemVersion]floatValue];
    if (version >= 10.0) {
        /// 大于等于10.0系统使用此openURL方法
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
     }
   }
    
}



@end
